/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.gcm.demo.server;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hs.mobile.service.device.DeviceService;

import java.util.Date;

import com.hs.mobile.model.Device;
import com.hs.mobile.model.Register;
import com.hs.mobile.service.device.DeviceService;
import com.hs.mobile.service.register.RegisterService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Simple implementation of a data store using standard Java collections.
 * <p>
 * This class is thread-safe but not persistent (it will lost the data when the
 * app is restarted) - it is meant just as an example.
 */
public final class Datastore {

  protected static final Logger logger = Logger.getLogger("DataStore");
  private static final List<String> regIds = new ArrayList<String>();
  
  private static DeviceService deviceService;
  private static RegisterService registerService;
  
  private Datastore() {
    throw new UnsupportedOperationException();
  }
  
  private static DeviceService getDeviceService() {
	  if( deviceService == null ) {
		  ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		  deviceService = (DeviceService)appContext.getBean("deviceService");
	  }
	  return deviceService;
  }
  
  private static RegisterService getRegisterService() {
	  if( registerService == null ) {
		  ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		  registerService = (RegisterService)appContext.getBean("registerService");
	  }
	  return registerService;
  }

  /**
   * Registers a device.
   */
  public static void register(String regId, String categoryId ) {
    logger.info("Registering " + regId);
    DeviceService deviceService = getDeviceService();
    List<Device> list = getDeviceService().getDeviceByIdGCM(regId);
    if( list.size() == 0 ) {
		Device device = new Device();
		device.setDeviceId(regId);
		device.setRegisterDate(new Date() );
		device.setStatus(1);
		deviceService.save(device);
    }
    Register register = new Register();
    if( list.size() > 0 ) {
    	register.setIdDevice(list.get(0).getId());
    } else {
    	register.setIdDevice(1);
    }
    register.setIdCategory(Long.parseLong(categoryId));
    register.setRegisterDate(new Date());
    getRegisterService().save(register);
	logger.debug("===========---- Register ------============= >>>" );
  }

  /**
   * Unregisters a device.
   */
  public static void unregister(String regId, String categoryId ) {
    logger.info("Unregistering " + regId);
    DeviceService deviceService = getDeviceService();
   	List<Device> listDevice = deviceService.getDeviceByIdGCM(regId);
   	for( Device device : listDevice ) {
	   	device.setDeviceId(regId);	   	
	   	device.setRegisterDate(new Date() );
	   	device.setStatus(0);
	   	deviceService.save(device);
   	}
   	logger.debug("===========---- Un-Register/Expired date ------============= >>>" );
  }
  
  public static void re_register( String regId, String categoryId  )
  {
  	DeviceService deviceService = getDeviceService();
   	List<Device> listDevice = deviceService.getDeviceByIdGCM(regId);
   	for( Device device : listDevice ) {
   		long id = device.getId();
   		List<Register> listRegisters = getRegisterService().getRegistersByDeviceIdandCategoryId(id, Long.parseLong( categoryId) );
   		if( listRegisters.size() == 0 ) {
   			Register register = new Register();
   			register.setIdDevice(id);
   			register.setRegisterDate(new Date());
   			register.setIdCategory(Long.parseLong(categoryId));
   			getRegisterService().save(register);
   		}
	   	device.setDeviceId(regId);
	   	device.setRegisterDate(new Date() );
	   	device.setStatus(1);
	   	deviceService.update(device);
   	}
   	logger.debug("===========---- Un-Register/Expired date/Or Register new Service  ------============= >>>" );
  }

  /**
   * Updates the registration id of a device.
   */
  public static void updateRegistration(String oldId, String newId) {
    logger.info("Updating " + oldId + " to " + newId);
    synchronized (regIds) {
      regIds.remove(oldId);
      regIds.add(newId);
    }
  }

  /**
   * Gets all registered devices.
   */
  public static List<String> getDevices() {
    synchronized (regIds) {
      return new ArrayList<String>(regIds);
    }
  }
  
  public static List<Device> getListDevices() {
	  return getDeviceService().getAllDevices();
  }

}
